//
//  XLocalImage.swift
//  Ymh
//
//  Created by yoctech on 2021/12/3.
//

import UIKit

class XLocalImage: NSObject {
    static let fileManager = FileManager.default
    static let rootPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    static let folderName = "localImage"
    class func saveImage(_ image: UIImage) -> String {
        let imgData = image.jpegData(compressionQuality: 1)
        let filePath = "\(rootPath)/\(folderName)/\(Date().timeIntervalSince1970)\(String.lx_random(length: 4)).jpg"
        
        fileManager.createFile(atPath: filePath, contents: imgData, attributes: nil)
        return filePath
    }
    
    class func localImage(_ filePath: String?) -> UIImage? {
        guard let filePath = filePath else { return nil }
        
        if fileManager.fileExists(atPath: filePath) {
            if let data = fileManager.contents(atPath: filePath) {
                return UIImage.init(data: data)
            }
        }
        return nil
    }
    
    class func removeImage(_ filePath: String?) {
        guard let filePath = filePath else { return }
        
        if fileManager.fileExists(atPath: filePath) {
            try? fileManager.removeItem(atPath: filePath)
        }
    }

}
